package com.inter.controller.travis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.inter.entity.agatewaytobeijing.JsonConstant;
import com.inter.entity.agatewaytobeijing.PackageOrderRefueling;
import com.inter.entity.agatewaytobeijing.querydeviceorder.response.DevicePackageOrder;
import com.inter.entity.agatewaytobeijing.querydeviceorder.response.ResponseQueryDeviceOrder;
import com.inter.entity.interentity.queryorder.request.RequestordersQuery;
import com.inter.entity.interentity.queryorder.request.RequestordersQueryDate;
import com.inter.entity.interentity.queryorder.response.ResponseordersQuery;
import com.inter.entity.interentity.queryorder.response.ResponseordersQueryData;
import com.inter.entity.interentity.queryorder.response.ResponseordersQueryRefuelingPackageList;
import com.inter.entity.interentity.queryorder.response.ResponseordersQueryTradeData;
import com.inter.entity.interentity.utils.UtilsInterfacesPackage;
import com.inter.entity.newpojo.response.responseBody.QueryOrderResponseBody;
import com.inter.entity.newpojo.response.subResponse.common.PackageOrder;
import com.inter.entity.newpojo.response.subResponse.common.RefuelingPackageList;
import com.inter.insideinterservice.newservice.TrunToQueryorderService;
import com.inter.service.PartnerProductPackageService;
import com.inter.service.PartnerService;
import com.inter.service.SequenceService;
import com.inter.service.agatewaytobeijing.GatewayToBeijingService;
import com.inter.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 查询当前设备所有的订单
 *
 * @author lm
 * @date 2018/8/31
 */
@RestController
@Api(description = "查询套餐订单信息")
@Slf4j
public class QueryOrderController {
    @Autowired
    SequenceService sequenceService;
    @Autowired
    PartnerService partnerService;
    @Autowired
    PartnerProductPackageService partnerProductPackageService;
    @Autowired
    GatewayToBeijingService toBeijingService;

    @CrossOrigin
    @RequestMapping(value = "queryOrder", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询订单", response = ResponseordersQuery.class)
    public String queryOrder(@ApiParam @RequestBody RequestordersQuery requestordersQuery) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curTime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        if (null == requestordersQuery || StringUtils.isBlank(JSON.toJSONString(requestordersQuery))) {
            log.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curTime);
            return jsonString;
        }
        String requestStr = JSON.toJSONString(requestordersQuery);
        log.info("【查询订单】请求：" + requestStr);
        if (StringUtils.isBlank(requestordersQuery.getSign())) {
            log.info("请求报文不合法:sign为空");
            jsonString = utils.dataWeiKong(connSeqNo, curTime);
            return jsonString;
        }
        String requestSign = requestordersQuery.getSign();
        if (null == requestordersQuery.getData()) {
            log.info("请求报文不合法:data为空");
            jsonString = utils.dataWeiKong(connSeqNo, curTime);
            return jsonString;
        }
        RequestordersQueryDate requestData = requestordersQuery.getData();
        if (StringUtils.isBlank(requestData.getPartnerCode()) || StringUtils.isBlank(requestData.getConnSeqNo()) || StringUtils.isBlank(requestData.getTradeTime()) || StringUtils.isBlank(requestData.getToken()) || StringUtils.isBlank(requestData.getTradeType()) || null == requestData.getTradeData()) {
            log.info("请求报文不合法:data参数不合法");
            jsonString = utils.dataWeiKong(connSeqNo, curTime);
            return jsonString;
        }
        String partnerCode = requestData.getPartnerCode();
        String secret = partnerService.findSecretByPartnerCode(partnerCode);
        String ConnSeqNo = requestData.getConnSeqNo();
        String tradeTime = requestData.getTradeTime();
        String token = requestData.getToken();
        String tradeType = requestData.getTradeType();
        String lang = requestData.getLang();

        /*计算签名：将请求体json转成String*/
        String str = JSON.toJSONString(requestData);
        // 将str拿去计算签名
        String sign = utils.calculateSignature(str);
        if (!requestSign.equalsIgnoreCase(sign)) {
            log.info("签名验证失败！");
            jsonString = utils.publicMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
            return jsonString;
        }
        if (StringUtils.isBlank(requestData.getTradeData().getDeviceId()) || null == requestData.getTradeData().getOrderType() || null == requestData.getTradeData().getOrderId() || null == requestData.getTradeData().getOrderStatus()) {
            log.info("请求报文不合法:tradeData的值为null或者为空");
            jsonString = utils.dataWeiKong(connSeqNo, curTime);
            return jsonString;
        }
        String deviceId = requestData.getTradeData().getDeviceId();
        String orderType = requestData.getTradeData().getOrderType();
        String orderId = requestData.getTradeData().getOrderId();
        String orderStatus = requestData.getTradeData().getOrderStatus();
        /*响应*/
        List<ResponseordersQueryTradeData> responseTradeData = new ArrayList<ResponseordersQueryTradeData>();

        /*现在去请求北京企业网关做订单查询*/
        ResponseQueryDeviceOrder orderQuery = toBeijingService.queryDeviceOrder(deviceId, orderId, orderStatus, orderType, partnerCode, secret);
        if (null != orderQuery && JsonConstant.RET_CODE_0000.equals(orderQuery.getCode()) && null != orderQuery.getData() && null != orderQuery.getData().getPackageOrder() && !orderQuery.getData().getPackageOrder().isEmpty()) {
            ResponseordersQueryTradeData tra = null;
            for (DevicePackageOrder order : orderQuery.getData().getPackageOrder()) {
                String packageNameEN = partnerProductPackageService.queryPackageName(order.getPackageName(), partnerCode);
                List<ResponseordersQueryRefuelingPackageList> lists = new ArrayList<ResponseordersQueryRefuelingPackageList>();
                ResponseordersQueryRefuelingPackageList refueling = null;

                if (null != order.getRefuelingPackageList() && !order.getRefuelingPackageList().isEmpty()) {
                    //有加油包
                    for (PackageOrderRefueling re : order.getRefuelingPackageList()) {
                        //开始准备数据
                        refueling = new ResponseordersQueryRefuelingPackageList();
                        refueling.setRefpackageName("");
                        refueling.setRefpackageCode("");
                        refueling.setRefpackageFlow(re.getRefpackage_flow());
                        refueling.setRefpackageOrderDate(re.getRefpackage_order_date());
                        lists.add(refueling);
                    }
                }

                if (!"DP20190312000368".equalsIgnoreCase(order.getPackageCode()) && !"DP20190513000751".equalsIgnoreCase(order.getPackageCode()) &&
                        !"DP20191012001731".equalsIgnoreCase(order.getPackageCode()) && !"DP20180806000121".equalsIgnoreCase(order.getPackageCode())) {
                    //开始准备回去的数据
                    tra = new ResponseordersQueryTradeData();
                    tra.setOrderId(order.getOrderId());
                    tra.setDeviceId(order.getDeviceId());
                    tra.setPackageCode(order.getPackageCode());
                    if ("en".equals(lang)) {
                        tra.setPackageName(packageNameEN);
                    } else {
                        tra.setPackageName(order.getPackageName());
                    }
                    tra.setPackageType(order.getPackageType());
                    tra.setOrderStatus(order.getOrderStatus());
                    tra.setBuyType(order.getBuyType());
                    tra.setOrderPeriod(order.getOrderPeriod());
                    tra.setFlow(order.getFlow());
                    tra.setUsedFlow(order.getUsedFlow());
                    tra.setFlowUseRate(order.getFlowUseRate());
                    tra.setOrderUsedFlow(order.getUsedFlow());
                    tra.setOrderDate(order.getOrderDate());
                    tra.setActiveDate(order.getActiveDate());
                    tra.setExpireDate(order.getExpireDate());
                    tra.setIsOrderRefuelingPackage(null);
                    tra.setRefuelingPackageList(lists);
                    responseTradeData.add(tra);

                }
            }
            //在外面准备data
            ResponseordersQueryData data = new ResponseordersQueryData();
            data.setConnSeqNo(connSeqNo);
            data.setPartnerCode(partnerCode);
            data.setToken(token);
            data.setTradeType(tradeType);
            data.setTradeTime(curTime);
            data.setTradeRstCode(1000);
            data.setTradeRstMessage("success");
            data.setTradeData(responseTradeData);

            ResponseordersQuery responseQueryorder = new ResponseordersQuery();
            responseQueryorder.setData(data);
            responseQueryorder.setSign(MD5.calcMD5(JSON.toJSONString(data)));
            // 返回给调用者的报文
            log.info("【查询全部订单】成功响应：" + JSON.toJSONString(responseQueryorder));
            return JSON.toJSONString(responseQueryorder);
        }

        ResponseordersQueryData data = new ResponseordersQueryData();
        data.setConnSeqNo(connSeqNo);
        data.setPartnerCode(partnerCode);
        data.setToken(token);
        data.setTradeType(tradeType);
        data.setTradeTime(curTime);
        data.setTradeRstCode(1003);
        data.setTradeRstMessage("The order was not queried;未查询到订单");
        data.setTradeData(responseTradeData);

        ResponseordersQuery responseQueryorder = new ResponseordersQuery();
        responseQueryorder.setData(data);
        responseQueryorder.setSign(MD5.calcMD5(JSON.toJSONString(data)));
        // 返回给调用者的报文
        log.info("【查询订单】未成功获取结果响应：：" + JSON.toJSONString(responseQueryorder));
        return JSON.toJSONString(responseQueryorder);
    }
}
